var express = require('express');
var router = express.Router();

var register = require('../models/register.js');
var note = require('../models/note.js');
var comment = require('../models/comment.js');

var async = require('async');
var ObjectID = require('mongodb').ObjectID;

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/register',function(req,res,next){
  var user_info = new register({
    user: req.body.user,
    password: req.body.password,
    email: req.body.email,
    img: req.body.img,
    date: get_now_date()
  });
  user_info.save(function(err,user){
    if(err){
      req.flash('error',err);
      return res.json({status:500,message:'后台错误'});
    }
    return res.json({status: 200,message:'注册成功'})
  });
});

router.get('/user_info',function(req,res,next){
  register.get({},function(err,data){
    if(err){
      return res.json({valid:false})
    }
    if(data && data.length > 0){
      for(var i in data){
        if(data[i].user == req.query.user){
          return res.json({valid:false})
        }
      }
      return res.json({valid:true})
    }
    return res.json({valid:true})
  });
});

router.post('/signin',function(req,res,next){
  register.get({user: req.body.user},function(err,data){
    if(err){
      return res.json({status:500,message:'后台错误'})
    }
    if(data && data.length > 0){
      if(data[0].password == req.body.password){
        req.session._id = data[0]._id;
        return res.json({status: 200,message:'登录成功',user_id: req.session._id})
      }else{
        return res.json({status:400,message:'密码错误'})
      }
    }else{
     return res.json({status: 400,message:'用户名不存在'})
    }
  })
});

//帖子部分
router.get('/get_all_note',function(req,res,next){
  var note_info;
  async.series([
        function(callback){
          note.get(null,function(err,data) {
            if (err) {
              return res.json({status: 500, message: '后台错误'})
            }
            note_info = data;
            callback(null,data)
          })
        },
        function(callback) {
          async.concat(note_info,
              function (item, callback) {
                register.get({_id: new ObjectID(item.user)}, function (err, user) {
                  if (err) {
                    return res.json({status: 500, message: '后台错误'})
                  }
                  if (user && user.length > 0) {
                    item.user = user;
                    callback(null, item)
                  }
                });
              },
              function (err, data) {
                callback(null,data)
              });
        }
      ],
      function(err,results){
        res.json({status: 200, data: results[0]})
      })
});

router.get('/get_user_note',function(req,res,next){
  note.get({user:req.query.user},function(err,data){
    if(err){
      return res.json({status:500,message:'后台错误'})
    }
    register.get({_id: new ObjectID(req.query.user)},function(err,user){
      if(err){
        return res.json({status:500,message:'后台错误'})
      }
      if(user && user.length > 0){
        for(var i in data){
          data[i].user = user;
        }
        res.json({status:200, data: data})
      }
    });
  });
});

router.get('/get_note',function(req,res,next){
  var note_info;
  async.series([
          function(callback){
            note.get({_id:new ObjectID(req.query.note_id)},function(err,data) {
              if (err) {
                return res.json({status: 500, message: '后台错误'})
              }
              note_info = data;
              callback(null,data)
            })
          },
          function(callback){
            register.get({_id: new ObjectID(note_info[0].user)},function(err,user){
              if(err){
                return res.json({status:500,message:'后台错误'})
              }
              if(user && user.length > 0){
                note_info[0].user = user;
                callback(null,note_info);
              }
            });
          },
          function(callback){
            comment.get({note_id: req.query.note_id},function(err,data){
              if(err){
                return res.json({status:500,message:'后台错误'})
              }
              if(data && data.length > 0){
                note_info[0].comment = data;
                callback(null,note_info);
              }else{
                note_info[0].comment = '';
                callback(null,note_info);
              }
            })
          },
        function(callback) {
          if (note_info[0].comment == '') {
            callback(null, note_info)
          } else {
            async.concat(note_info[0].comment,
                function(item,callback){
                  register.get({_id: new ObjectID(item.user)}, function (err, user) {
                    if (err) {
                      return res.json({status: 500, message: '后台错误'})
                    }
                    if (user && user.length > 0) {
                      item.user = user;
                      callback(null, item)
                    }
                  });
                },
                function(err,result){
                  callback(null,note_info)
                })
          }
        }
      ],
      function(err,result){
        return res.json({status:200, data: note_info})
      })
});

router.post('/create_note',function(req,res,next){
  var note_info = new note({
    user: req.query.user,
    title: req.body.title,
    content: req.body.content,
    comment_num: 0,
    created_at: get_now_date(),
    updated_at: get_now_date()
  });
  note_info.save(function(err,data){
    if(err){
      return res.json({status:500,message:"后台错误"})
    }
    return res.json({status:200,message:"帖子发表成功"})
  })

});

router.post('/update_note',function(req,res,next){
  var note_info = {
    _id: req.body._id,
    title: req.body.title,
    content: req.body.content,
    updated_at: get_now_date()
  };
  note.replace(note_info,function(err){
    if(err){
      return res.json({status:500,message:'后台错误'})
    }
    return res.json({status:200,message:'修改帖子成功'})
  })
});

router.get('/delete_note',function(req,res,next){
  async.series([
        function(callback){
          note.delete(req.query._id,function(err,data){
            if(err){
              return res.json({status:500,message:'后台出错'})
            }
            callback(null,data);
          })
        },
        function(callback){
          comment.delete({note_id: req.query._id },function(err,data){
            if(err){
              return res.json({status:500,message:'后台出错'})
            }
            callback(null,data);
          })
        }
      ],
      function(err,result){
        if(err){
          res.json({status:500,message:'删除帖子失败'})
        }
        return res.json({status:200,message:'删除帖子成功'})
      }
  )
});

router.get('/del_comment',function(req,res,next){
  var num;
  async.series([
        function(callback){
          comment.delete({_id:new ObjectID(req.query._id)},function(err,data) {
            if (err) {
              return res.json({status: 500, message: '后台出错'})
            }
            callback(null,data)
          })
        },
        function(callback){
          comment.get({note_id: req.query.note_id},function(err,data){
            if(err){
              return res.json({status:500,message:'后台错误'})
            }
            if(data && data.length > 0){
              num = data.length;
              callback(null,data.length);
            }else{
              num = 0;
              callback(null,0)
            }
          })
        },
        function(callback){
          note.replace_num({_id:req.query.note_id,comment_num: num},function(err,data){
            if(err){
              return res.json({status:500,message:'后台错误'})
            }
            callback(null,data)
          })
        }
      ],
      function(err,result){
        return res.json({status:200,message:'删除留言成功'})
      });
});

router.post('/add_comment',function(req,res,next){
  var num;
  var comment_info = new comment({
    user: req.body.user,
    note_id: req.body.note_id,
    content: req.body.content,
    created_at: get_now_date()
  });
  async.series([
        function(callback){
          comment_info.save(function(err,data){
            if(err){
              return res.json({status:500,message:"后台错误"})
            }
            callback(null,data)
          })
        },
        function(callback){
          comment.get({note_id: req.body.note_id},function(err,data){
            if(err){
              return res.json({status:500,message:'后台错误'})
            }
            if(data && data.length > 0){
              num = data.length;
              callback(null,num)
            }else{
              num = 0;
              callback(null,0)
            }
          })
        },
        function(callback){
          note.replace_num({_id:req.body.note_id,comment_num: num},function(err,data){
            if(err){
              return res.json({status:500,message:'后台错误'})
            }
            callback(null,data)
          })
        }
      ],
      function(err,result){
        return res.json({status:200,message:"留言成功"});
      });
});

module.exports = router;

function get_now_date(){
  var now_date = new Date();
  var year = now_date.getFullYear();
  var month=now_date.getMonth()+1>9 ? now_date.getMonth()+1 : '0'+(now_date.getMonth()+1);
  var data=now_date.getDate()>=10 ? now_date.getDate() : '0'+now_date.getDate();
  var time = now_date.getHours()>=10 ? now_date.getHours() : '0'+now_date.getHours();
  var minutes = now_date.getMinutes() >=10 ? now_date.getMinutes() : '0'+now_date.getMinutes();
  var date =year+'-'+month+'-'+data + ' ' +time+ '-' + minutes;
  return date;
}



